﻿using SaaS.Model.Dto.Auths;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Web.System.Services.Utils
{
    public static class OrganizationUnitFinder
    {
        public static IReadOnlyList<OrganizationUnitChildren> GetOrganizationUnitChildrens(IEnumerable<OrganizationUnitDto> organizations)
        {
            List<OrganizationUnitChildren> list = new List<OrganizationUnitChildren>();
            foreach (var item in organizations.Where(c => c.ParentId == null))
            {
                var organizationUnit = new OrganizationUnitChildren(item.Id, item.Name);
                organizationUnit.GetChildren(item.Id, organizations);
                list.Add(organizationUnit);
            }
            return list;
        }
        private static OrganizationUnitChildren GetChildren(this OrganizationUnitChildren organization, int parentId, IEnumerable<OrganizationUnitDto> organizations)
        {
            foreach (var item in organizations.Where(c => c.ParentId == parentId))
            {
                var children = organization.CreateChildrenOrganization(item.Id, item.Name);
                if (organizations.Any(c => c.ParentId == item.Id))
                    children.GetChildren(item.Id, organizations);
            }
            return organization;
        }
    }
}
